<?php
try {
    global $SMARTY,$DBobject;
    $referer = parse_url($_SERVER['HTTP_REFERER']);
    if ($referer['host'] == $GLOBALS['HTTP_HOST']) {
        switch ($_POST['action']) {
            case 'getPaymentStatus':
                $orderNo = $_POST['orderno'];
                $cart_obj = new Enrolment();
                $payment = $cart_obj->getPaymentStatus($orderNo);
                if ($payment) {
                    echo json_encode(['status'=>$payment[0]['payment_status']]);
                } else {
                    echo json_encode(['status'=>'P']);
                }
                exit;
            case 'ADDTOCART':
                $cart_obj = new Enrolment();
                if (!empty($_POST['enrolment']) && !empty($_POST['isClass']) && $_POST['enrolment'] == 'T'  && $_POST['isClass'] == 1) {
                    $trialWeekArr = array();
                    $trialWeekArr['week'][0] = $_POST['attr']['week'][0];
                    $_POST['attr'] = $trialWeekArr;
                }
                $response = $cart_obj->addToCart($_POST['product_id'], $_POST['attr'], $_POST['quantity'], $_POST['price'], null, $_POST['listing_id'], $_POST['isClass'], $_POST['enrolment']);
                $itemsCount = $cart_obj->NumberOfProductsOnCart();
                $subtotal = $cart_obj->GetSubtotal();
                $productsOnCart = $cart_obj->GetDataProductsOnCart();
                $SMARTY->assign('productsOnCart', $productsOnCart);
                $SMARTY->assign('itemNumber', $itemsCount);
                $SMARTY->assign('subtotal', $subtotal);
                $popoverShopCart= $SMARTY->fetch('templates/popover-shopping-cart.tpl');
                $productGA = $cart_obj->getProductInfo_GA($_POST['product_id'], $_POST['attr'], $_POST['quantity'], $_POST['listing_id']);
                echo json_encode([
                    'product' => $productGA,
                    'message' => $response . '<br><a style="font-weight:normal" href="/shopping-cart">去结算</a>',
                    'itemsCount' => $itemsCount,
                    'subtotal' => $subtotal,
                    'url' => 'http://'.$GLOBALS['HTTP_HOST'].'/shopping-cart',
                    'popoverShopCart' =>  str_replace(array('\r\n', '\r', '\n', '\t'), ' ', $popoverShopCart)
                ]);
                exit;
            
            case 'DeleteItem':
                $cart_obj = new Enrolment();
                $response = $cart_obj->RemoveFromCart($_POST['cartitem_id']);
                    $productGA = $cart_obj->getProductInfoByCartItem_GA($_POST['cartitem_id']);
                    $totals = $cart_obj->CalculateTotal($_SESSION['students']);
                $itemsCount = $cart_obj->NumberOfProductsOnCart();
                $cart = $cart_obj->GetDataCart();
                $productsOnCart = $cart_obj->GetDataProductsOnCart();
                $SMARTY->assign('productsOnCart', $productsOnCart);
                $SMARTY->assign('itemNumber', $itemsCount);
                $SMARTY->assign('subtotal', $totals['subtotal']);
                $SMARTY->assign('cart', $cart);
                $popoverShopCart= $SMARTY->fetch('templates/popover-shopping-cart.tpl');
                echo json_encode([
                    'product' => $productGA,
                    'itemsCount' => $itemsCount,
                    'response'=> $response,
                    'totals'=>$totals,
                    'popoverShopCart' =>  str_replace(array('\r\n', '\r', '\n', '\t'), ' ', $popoverShopCart)
                ]);
                exit;

            case 'updateCart':
                $cart_obj = new Enrolment();
                $updated_products = $cart_obj->UpdateQtyCart($_POST['qty']);
                $subtotals = $updated_products['subtotals'];
                $priceunits = $updated_products['priceunits'];
                $pricemodifier = $updated_products['pricemodifier'];
                $totals = $cart_obj->CalculateTotal($_SESSION['students']);
                $itemsCount = $cart_obj->NumberOfProductsOnCart();
                $cart = $cart_obj->GetDataCart();
                $productsOnCart = $cart_obj->GetDataProductsOnCart();
                $SMARTY->assign('productsOnCart', $productsOnCart);
                $SMARTY->assign('itemNumber', $itemsCount);
                $SMARTY->assign('subtotal', $totals['subtotal']);
                $SMARTY->assign('cart', $cart);
                $popoverShopCart= $SMARTY->fetch('templates/popover-shopping-cart.tpl');
                echo json_encode([
                    'itemsCount'=> $itemsCount,
                    'subtotals'=>$subtotals,
                    'pricemodifier'=>$pricemodifier,
                    'priceunits'=>$priceunits,
                    'totals'=>$totals,
                    'popoverShopCart' =>  str_replace(array('\r\n', '\r', '\n', '\t'), ' ', $popoverShopCart)
                ]);
                exit;

            case 'updatePostage':
                $ship_obj = new ShippingClass();
                  echo json_encode(array(
                  'postagefee'=> $ship_obj->getPostageByPostcode($_POST['postcode'])
                  ));
                exit;
            
            case 'addFavourite':
                $logged = false;
                $success = false;
                if (!empty($_SESSION['user']['public']['id'])) {
                    $logged = true;
                    $cart_obj = new Enrolment();
                    if ($res = $cart_obj->AddFavourite($_SESSION['user']['public']['id'], $_POST['productObjId'])) {
                        $success = true;
                    }
                }
                echo json_encode(array(
                'success'=>$success,
                'logged'=>$logged
                ));
                exit();
            
            case 'deleteFavourite':
                $logged = false;
                if (!empty($_SESSION['user']['public']['id'])) {
                    $logged = true;
                    $cart_obj = new Enrolment();
                    $res = $cart_obj->DeleteFavourite($_SESSION['user']['public']['id'], $_POST['productObjId']);
                }
                echo json_encode([
                    'error'=>$res['error'],
                    'success'=>$res['success'],
                    'logged'=>$logged
                ]);
                exit();
            
            case 'applyDiscount':
                $cart_obj = new Enrolment();
                $res = $cart_obj->ApplyDiscountCode($_POST['discount_code']);
                if ($res['error']) {
                    $_SESSION['error']= $res['error'];
                    $_SESSION['reApplydiscount']= ($res['reApplyAfterLogin'])?$_POST['discount_code']:'';
                    $_SESSION['post']= $_POST;
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#error');
                } else {
                    header('Location: '.$_SERVER['HTTP_REFERER']);
                }
                exit;
            
            case 'checkout1':
                if (!empty($_POST['postageID'])) {
                    $_SESSION['smarty']['selectedShippingPostcode'] = $_POST['postcodefield'];
                    $_SESSION['smarty']['selectedShippingFee'] = $_POST['shipFee'];
                    $_SESSION['smarty']['selectedShipping'] = $_POST['shipMethod'];
                    $_SESSION['smarty']['postageID'] = $_POST['postageID'];
                  
                    $sql = "SELECT * FROM tbl_postcode WHERE postcode_postcode = :postcode";
                    $params = array(":postcode"=>$_POST['postcodefield']);
                    $res = $DBobject->wrappedSql($sql, $params);
                    if (!empty($res[0])) {
                        $_SESSION['smarty']['selectedShippingState'] = $res[0]['postcode_state'];
                        if (count($res) == 1) {
                            $_SESSION['smarty']['selectedShippingSuburb'] = $res[0]['postcode_suburb'];
                        }
                    }
                }
              
                if ($CONFIG->checkout->attributes()->guest != 'true' && empty($_SESSION['user']['public']['id'])) {
                    $_SESSION['redirect'] = "/checkout";
                    header("Location: /login");
                    exit();
                }
                $_SESSION['checkoutstep'] = 1;
                header('Location: /checkout');
                exit;
            
            case 'checkout2':
                $_SESSION['postageID'] = $_POST['postageID'];
                $_SESSION['address'] = $_POST['address'];
                $ssum = $_POST['address']['S']['address_name'] .' ';
                $ssum .= $_POST['address']['S']['address_state'] .' ';
                $ssum .= $_POST['address']['S']['address_suburb'] .' ';
                $ssum .= $_POST['address']['S']['address_country'] .' ';
                $ssum .= $_POST['address']['S']['address_line1'] .' ';
                $ssum .= $_POST['address']['S']['address_postcode'] .' ';
                $ssum .= substr_replace($_POST['address']['S']['address_telephone'], '****', 3, 4) . '<br />';
                $_SESSION['comments'] = $_POST['comments'];
                $_SESSION['agreed_tc'] = $_POST['accept'];
                if ($_POST['comments']) {
                    $ssum .= '运费说明: ' . $_POST['comments'] . '<br />';
                } else {
                    $ssum .= '无需运费 <br />';
                }
        
                $cart_obj = new Enrolment();
                $countClassOnCart = $cart_obj->GetQtyClassOnCart();
          
                $_SESSION['checkoutstep'] = 2;
          
                echo json_encode(array(
                    'response'=> true,
                    'billing'=> $bsum,
                    'shipping'=> $ssum,
                    'countClassOnCart'=> $countClassOnCart,
                    'comments'=> $_POST['comments']
                ));
                exit;

            case 'getShippingFees':
                $_SESSION['address'] = $_POST['address'];
            
                $ship_obj = new ShippingClass();
                $cart_obj = new Enrolment();
            
                $methods = $ship_obj->getShippingMethods($cart_obj->NumberOfProductsOnCart());
            
                echo json_encode(array(
                    'shippingMethods'=> $methods,
                    'billing'=> $_POST['address']['B'],
                    'shipping'=> $_POST['address']['S'],
                    'same'=> $_POST['address']['same_address']
                ));
                exit;

            case 'studentTemplate': //RETURN STUDENT TEMPLATE WITH CLASSES ON CART
                $enrol_obj = new Enrolment();
                $productsOnCart = $enrol_obj->GetDataProductsOnCart();
                $SMARTY->assign('productsOnCart', $productsOnCart);
                $SMARTY->assign('cnt', $_POST['cnt']);
                $template = $SMARTY->fetch('student.tpl');
                echo json_encode(array(
                    "error" => null,
                    "success" => true,
                    "template" => $template
                ));
                
                exit;
            
            case 'validateNewStudent':
                $error = null;
                $success = true;
                $existingName = array();
                $existingDOB = array();
                foreach ($_POST['student'] as $key => $student) {
                    $stdFullName = $student['student_name'];
                    if (!empty($student) && !empty($student['student_name']) && !empty($student['student_sex']) && !empty($student['student_dob'])) {
                        if (in_array($stdFullName, $existingName) || in_array($student['student_dob'], $existingDOB)) {
                            $error = "存在同名且出生日期相同的学生，请联系我们解决该问题。";
                            $success = false;
                            break;
                        }
                    }
                    $existingName[] = $stdFullName;
                    $existingDOB[] = $student['student_dob'];
                }
                echo json_encode(array(
                    "error" => $error,
                    "success" => $success
                ));
                exit;

            case 'PreSelectClasstermStudent':
                $_SESSION['preSelected'][$_POST['student_id']][$_POST['term_object_id']][$_POST['class_object_id']] = 1;
                $error = '';
                $success = true;
            
                echo json_encode(array(
                    "error" => $error,
                    "success" => $success
                ));
                exit;
            
            case 'setStudent': //STORE STUDENT INFO IN SESSION - IT DOESN'T CREATE IT
                $studentArr = array();
                $classtermArr = array();
                $classtermStudentArr = array();
                $enrol_obj = new Enrolment();
                $productsOnCart = $enrol_obj->GetDataProductsOnCart();
                $error = null;
                $success = true;
                $remove = array();
                $hasEnrolmentArr = array();
                $trialListArr =  array();
                $missingDetails = '';
            
                foreach ($_POST['student'] as $key => $student) {
                    $stdFullName = $student['student_name'];
                    if (!empty($student) && !empty($student['student_name']) && !empty($student['student_sex']) && !empty($student['student_dob'])) {
                        $studentArr[] = $student;
                        if (!empty($student['cartitem_id'])) {
                            foreach ($student['cartitem_id'] as $ct => $val) {
                                if (empty($classtermArr["{$ct}"])) {
                                    $classtermArr["{$ct}"] = $val;
                                } else {
                                    $classtermArr["{$ct}"] = $classtermArr["{$ct}"] + $val;
                                }
                                if ($val) {
                                    $fullName = urlSafeString($student['student_name']);
                                    $classtermStudentArr["{$fullName}"] = $student['student_name'];
                                
                                    // Check current enrolments
                                    if (!empty($student['student_id'])) {
                                        foreach ($productsOnCart as $item) {
                                            if ($item['cartitem_id'] == $ct && !$enrol_obj->ValidateStudentEnrolment($student['student_id'], $item['cartitem_product_id'])) {
                                                $hasEnrolment[] =  $student['student_name'] . ' 目前就读于所选课程。';
                                                break;
                                            }
                                        }
                                    } else {
                                    // Check for multiple trials for a single student
                                        foreach ($productsOnCart as $item) {
                                            if ($item['cartitem_id'] == $ct && $item['cartitem_enrolment_type'] == 'T') {
                                                if (in_array($fullName.$student['student_dob'], $trialListArr)) {
                                                    $hasEnrolment[] =  $student['student_name'] . ' 只能有一节体验课程。';
                                                    break;
                                                }
                                                $trialListArr[]= $fullName.$student['student_dob'];
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    } else {
                        if (!empty($student) && (empty($student['student_name']) || empty($student['student_dob']))) {
                            $missingDetails = '有一个学生的信息没有填写完整，请设置姓名、性别和生日。';
                        }
                        $remove[] = $key;
                    }
                }
            
                if (!empty($hasEnrolment)) {
                    $error = implode("<br>", $hasEnrolment);
                    $success = false;
                } else {
                    $classterm2 = array();
                    foreach ($productsOnCart as $item) {
                        if (!empty($item['cartitem_class_flag'])) {
                            $qty = $classtermArr["{$item['cartitem_id']}"];
                            /* if(empty($qty) || $item['cartitem_quantity'] != $qty ){
	    					$error = "The number of selected classes doesn't match with the number of classes associated to students";
	    					$success = false;
                            } */
                            if (!empty($qty)) {
                                $classterm2["{$item['cartitem_id']}"] = $qty;
                            } else {
                                $error = empty($missingDetails)?"有一个课程没有选择学生":$missingDetails;
                                $success = false;
                            }
                        }
                    }
                }
                if (!empty($classterm2)) {
                    $res = $enrol_obj->UpdateQtyCart($classterm2);
                    if (!empty($res['error'])) {
                        $error= implode('<br>', $res['error']) .'<br>请联系我们获取更多信息。';
                    }
                }
                $_SESSION['students'] = $studentArr;
                $totals = $enrol_obj->CalculateTotal($_SESSION['students']);
                if (empty($error)) {
                    $_SESSION['checkoutstep'] = 3;
                }
            
                echo json_encode(array(
                    "error" => $error,
                    "success" => $success,
                    'totals'=>$totals,
                    'classtermStudentArr' => $classtermStudentArr,
                    'remove'=>$remove,
                    'hasEnrolmentArr' => $hasEnrolmentArr
                ));
        
                exit;
                
            case 'placeOrder':
//            array(3) { ["arg1"]=> string(12) "process/cart" ["action"]=> string(10) "placeOrder" ["payment-method"]=> string(2) "wx" }
                $cart_obj = new Enrolment();
                $order_cartId = $cart_obj->cart_id;
                $orderData = $cart_obj->GetDataCart($order_cartId);
                $itemNumber = $cart_obj->NumberOfProductsOnCart($order_cartId);
                
                if (!empty($_SESSION['address']['S']) && !empty($_SESSION['user']['public']['id']) && !empty($itemNumber) && !empty($orderData['cart_user_id']) && ($_SESSION['user']['public']['id'] == $orderData['cart_user_id'])) {
                    // CREATE STUDENTS AND ENROL STUDENTS
                    $orderItems = $cart_obj->GetDataProductsOnCart($order_cartId);
                    $students_cnt = 0;
                    $classes_cnt=0;
                    $invalid_students=false;
                    $pr_classes_ck = array();
                    $create = 0;
                    
                    foreach ($orderItems as $item) {
                        if ($item['cartitem_class_flag'] == 1 && empty($pr_classes_ck["{$item['cartitem_id']}"])) {
                            $pr_classes_ck["{$item['cartitem_id']}"]=1;
                            $classes_cnt=$classes_cnt+intval($item['cartitem_quantity']);
                        }
                    }

                    if (!empty($_SESSION['students'])) {
                        $member_obj = new Member();
                        $_TEMP_STUDENTS_RES = $member_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
                        $_TEMP_STUDENTS = array();
                        foreach ($_TEMP_STUDENTS_RES as $st) {
                            $_TEMP_STUDENTS[] = $st['student_id'];
                        }
                        foreach ($_SESSION['students'] as $student) {
                            if (empty($student['student_id'])) {
                                $create++;
                            } else {
                                if (!in_array($student['student_id'], $_TEMP_STUDENTS)) {
                                    $invalid_students = true;
                                    break;
                                }
                            }
                            foreach ($orderItems as $item) {
                                if (!empty($student['cartitem_id'][$item['cartitem_id']])) {
                                    $students_cnt++;
                                }
                            }
                        }
                    }

                    //验证学生和课程的关系
                    if ($students_cnt != $classes_cnt || $invalid_students) {
                        //$to = "readysteadygokids@gmail.com-dev,online@them.com.au,readysteadygokids@gmail.com-dev";
                        //sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), 'Front-end (A)No/Wrong Students!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($_POST, true)." </br> CART: ".print_r($orderItems, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}");
                        $_SESSION['error'] = "出错了。所选学生与课程数不匹配。请选择与课程数量相等的学生。";
                        if ($invalid_students && !empty($_TEMP_STUDENTS_RES)) {
                            $_SESSION['students'] = $_TEMP_STUDENTS_RES;
                        }
                        header("Location: /checkout#error");
                        die();
                    }
                    
                    //THIS IS TRYING TO TRACE ERROR;
                    $isGuest = false;
                    $user_obj = new Member();
                    $values = array();
                    //var_dump($_SESSION['user']);exit;
                    $values['user_id'] = $_SESSION['user']['public']['id'];
                    $values['user_email'] = $_SESSION['user']['public']['email'];
                    $values['user_gname'] = $_SESSION['user']['public']['gname'];
                    $values['user_surname'] = '';
                    $values['user_want_promo'] = $_SESSION['address']['wantpromo']?1:0;
                    
                    $user_obj->UpdateDetails($values);
                    
                    // SAVE BILLING AND SHIPPING ADDRESS
                    $shipID = $user_obj->InsertNewAddress(array_merge(array(
                        'address_user_id' => $_SESSION['user']['public']['id']
                    ), $_SESSION['address']['S']));
                    if (empty($shipID)) {
                        $_SESSION['error']= '保存地址出错，请再试一次。';
                        $_SESSION['post']= $_POST;
                        header("Location: ".$_SERVER['HTTP_REFERER']."#error");
                        die();
                    }

                    $orderNumber = $order_cartId.'-'.date("is");
            
                    $shippingFee = 0;

                    $totals = $cart_obj->CalculateTotal($_SESSION['students']);
                    $chargedAmount = $totals['total'] + $shippingFee;
                    $surchargePer = floatval($CONFIG->payment_gateway->surcharge_percentage) / 100;
                    $surcharge = ($_POST['payment-method'] == 'cc' && ($chargedAmount > 0)  && ($chargedAmount > 0))? round($chargedAmount * $surchargePer, 2) : 0;
                    $chargedAmount += $surcharge;
                    $gst = round(($totals['GST_Taxable'] + $shippingFee) * 100 / ($TAX_RATE + 100), 2);
                    $params = array(
                        'payment_billing_address_id' => $shipID,
                        'payment_shipping_address_id' => $shipID,
                        'payment_transaction_no' => $orderNumber,
                        'payment_cart_id' => $order_cartId,
                        'payment_user_id' => $values['user_id'],
                        'payment_subtotal' => $totals['subtotal'],
                        'payment_discount' => $totals['discount'],
                        'payment_shipping_fee' => $shippingFee,
                        'payment_shipping_method' => '',
                        'payment_shipping_comments' =>  $_SESSION['comments'],
                        'payment_status' => 'P',
                        'payment_additional_description' =>  '',
                        'payment_additional' =>  0,
                        'payment_surcharge' =>  $surcharge,
                        'payment_payee_name' => $_POST['cc']['name'],
                        'payment_charged_amount' => $chargedAmount,
                        'payment_total' => $chargedAmount,
                        'payment_gst' => $gst,
                        'payment_method' => '',
                        'next_payment_date' => $_POST['nextpayment']
                    );
                    $pay_obj = new PaymentCommBank($params);
                    $response = false;

                    try {
                        $CCdata =  array('amount'=>$chargedAmount);
                        if (!empty($_POST['cc'])) {
                            $CCdata = array_merge($CCdata, $_POST['cc']);
                        }
                        $pay_obj->PreparePayment($CCdata);
                    
                        $subject ='澳睿跑 (Ready Steady Go Kids) | 订单确认';
                    
                        // ORDER STATUS
                        $status = 1; // Approved - No payment
                    
                        $bankTransfer = 0;
                        //CREDIT CARD PAYMENT
                        if ($_POST['payment-method'] == 'cc' && !empty($chargedAmount) && ($chargedAmount > 0)) {
                            $status = 2; // Approved - Credit Card - Full
                            $response = $pay_obj->Submit();
                            $paymentId = $pay_obj->GetPaymentId();
                            $subject ='澳睿跑 (Ready Steady Go Kids) | 收到付款';
                    
                        // BANK TRANSFER - NOT CREDIT CARD
                        } elseif ($_POST['payment-method'] == 'bt' && !empty($chargedAmount) && ($chargedAmount > 0)) {
                            $status = 7; // Pending - Bank Transfer - Full
                            $bankTransfer = 1;
                            $params['payment_method'] = 'Bank Transfer';
                            if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                                $response = true;
                            }
                            
                            // TRIAL ONLY WHEN CHARGED-AMOUNT IS ZERO (0)
                        } elseif ($_POST['payment-method'] == 'wx' && !empty($chargedAmount) && ($chargedAmount > 0)) {
                            $status = 11; // Pending - Wechat Pay - Full
                            $params['payment_method'] = 'Wechat Pay';
                            if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                                $response = true;
                            }

                            // TRIAL ONLY WHEN CHARGED-AMOUNT IS ZERO (0)
                            //union pay
                        } elseif ($_POST['payment-method'] == 'un' && !empty($chargedAmount) && ($chargedAmount > 0)) {
                            $status = 12; // Pending - Union Pay - Full
                            $params['payment_method'] = 'Union Pay';
                            if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                                $response = true;
                            }

                            // TRIAL ONLY WHEN CHARGED-AMOUNT IS ZERO (0)
                            // alipay
                        } elseif ($_POST['payment-method'] == 'al' && !empty($chargedAmount) && ($chargedAmount > 0)) {
                            $status = 13; // Pending - Alipay - Full
                            $params['payment_method'] = 'Alipay';
                            if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                                $response = true;
                            }
                        } else {
                            // TRIAL ONLY WHEN CHARGED-AMOUNT IS ZERO (0)
                            $params['payment_status'] = 'A';
                            $params['payment_method'] = 'No payment required';
                            if ($paymentId = $pay_obj->StorePaymentRecord($params)) {
                                $response = true;
                            }
                        }
                    } catch (Exception $e) {
                        $_SESSION['error'] = $e;
                    }

                    if ($response) {
                        //订单提交成功
                        $cart_obj->CloseCart();
                        $pay_obj->SetOrderStatus($paymentId, $status);
                        $_SESSION['orderNumber'] = $orderNumber;
                
                        try {
                            // 创建学生 并 报名课程
                            if (!empty($_SESSION['students'])) {
                                $member_obj = new Member();
                                foreach ($_SESSION['students'] as $student) {
                                    if (empty($student['student_id'])) {
                                        $student['student_id'] = $member_obj->addStudent($values['user_id'], $student);
                                    }
                                    foreach ($orderItems as $item) {
                                        if (!empty($student['cartitem_id'][$item['cartitem_id']])) {
                                            foreach ($item['attributes'] as $attr) {
                                                if ($attr['cartitem_attr_attribute_name'] == 'week') {
                                                    $cart_obj->addEnrolmentByClasstermId($student['student_id'], $item['cartitem_product_id'], $attr['cartitem_attr_attr_value_name'], $item['cartitem_enrolment_type'], 1, $paymentId);
                                                }
                                            }
                                        }
                                    }
                                }
                                $_SESSION['students'] = $user_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
                            }
                        } catch (Exception $e) {
                            $to = "liu.chang@chinaott.net";
                            sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), 'Front-end (A)ERROR adding Students!!', "Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($_POST, true)." </br> CART: ".print_r($orderItems, true)."</br>student cnts: {$students_cnt}</br>class cnts: {$classes_cnt}");
                            //$_SESSION['error'] .= "Your payment was made successfully, but something went wrong creating your enrolment! Please call 1300 766 892.";
                            //$_SESSION['students'] = $member_obj->GetStudentsByUserId($_SESSION['user']['public']['id']);
                        }
                    
                        try {
                            // SEND CONFIRMATION EMAIL
                            $SMARTY->assign("name", $_SESSION['user']['public']['gname']);
                            $user_obj = new Member();
                            $shipping = $user_obj->GetAddress($shipID);
                            $SMARTY->assign('shipping', $shipping);
                            $order = $cart_obj->GetDataCart($order_cartId);
                            $SMARTY->assign('order', $order);
                            $payment = $pay_obj->GetPaymentRecord($paymentId);
                            $SMARTY->assign('payment', $payment);
                            $orderItems = $cart_obj->GetDataProductsOnCart($order_cartId);
                            $SMARTY->assign('orderItems', $orderItems);
                            
                            // ================= Custom Messages ================
                            $sql = "SELECT email_additional_content FROM tbl_email_additional WHERE email_additional_id = :id ";
                            if ($res = $DBobject->wrappedSql($sql, array(':id' => 1))) {//Trial
                                $message = unclean($res[0]['email_additional_content']);
                                $SMARTY->assign('message', $message);
                            }
                            if ($res = $DBobject->wrappedSql($sql, array(':id' => 11))) {//CreditCard
                                $message = unclean($res[0]['email_additional_content']);
                                $SMARTY->assign('creditMessage', $message);
                            }
                            if ($res = $DBobject->wrappedSql($sql, array(':id' => 12))) {//Bank
                                $message = unclean($res[0]['email_additional_content']);
                                $SMARTY->assign('bankMessage', $message);
                            }

                                // ==================================================

                                $SMARTY->assign('bankTransfer', $bankTransfer);
                                $_SESSION['bankTransfer'] = $bankTransfer;
                                $SMARTY->assign('DOMAIN', "http://" . $GLOBALS['HTTP_HOST']);

                                $to = $_SESSION['user']['public']['email'];
                                $bcc = (string)$CONFIG->company->email_orders;
                    
                                $COMP = json_encode($CONFIG->company);
                                $SMARTY->assign('COMPANY', json_decode($COMP, true));
                            
                                $from = (string) $CONFIG->company->name;
                                $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                                $body= $SMARTY->fetch('email-confirmation.tpl');
                            if ($mailID = sendMail($to, $from, $fromEmail, $subject, $body, $bcc, $values['user_id'])) {
                                $pay_obj->SetInvoiceEmail($paymentId, $mailID);
                            }
                        } catch (Exception $e) {
                        }

                        //SET USED DISCOUNT CODE
                        if ($order['cart_discount_code']) {
                                $cart_obj->SetUsedDiscountCode($order['cart_discount_code']);
                                $discountData = $cart_obj->GetDiscountData($order['cart_discount_code']);
                            if ($discountData['discount_unlimited_use'] == '0') {
                                try {
                                    // SEND NOTIFICATION EMAIL
                                    $SMARTY->assign('user', $_SESSION['user']['public']);
                                    $SMARTY->assign('discount', $discountData);
                                    $buffer= $SMARTY->fetch('email-discount.tpl');
                                    $to = "lc918.student@sina.com";
                                    $bcc = "";
                                    $from = str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                                    $fromEmail = 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']);
                                    $subject = 'A discount code has been used.';
                                    $body = $buffer;
                                    $mailID = sendMail($to, $from, $fromEmail, $subject, $body, $bcc);
                                } catch (Exception $e) {
                                }
                            }
                        }
                
                        $_SESSION['checkoutstep'] = '';
                        $_SESSION['preSelected'] = '';
                
                        // OPEN NEW CART
                        $cart_obj->CreateCart($_SESSION['user']['public']['id']);
                
                        // REDIRECT TO THANK YOU PAGE
                        //header('Location: /checkout-completed');
                        header('Location: /payment?orderno='.$orderNumber.'&pmethod='.$_POST['payment-method']);
                        exit;
                    } else {
                        if ($error_msg = $pay_obj->GetErrorMessage()) {
                            $_SESSION['error'] .= ' '. $error_msg;
                        } else {
                            $_SESSION['error'] .= '付款失败，验证信息并重试。';
                        }
                    }
                } else {
                    $_SESSION['error'] .= '您的会话已过期，请再试一次。';
                }
                    $_SESSION['post']= $_POST;
                    header('Location: '.$_SERVER['HTTP_REFERER'].'#error');
                exit;
        }
        die('@');
    } else {
        header('Location: /404');
          die();
    }
} catch (Exception $e) {
    $post_vars = $_POST;
    $post_vars['cc'] = '';
    $to = "lc918.student@sina.com";
    sendMail($to, (string) $CONFIG->company->name, 'noreply@' . str_replace("www.", "", $GLOBALS['HTTP_HOST']), 'Front-end - SCRIPT ERROR - PAYMENT PROCESS', "Error: {$e} </br>Order: ".$order_cartId.'-'.date("is")."</br> Session: ".print_r($_SESSION, true)." </br> Post: ".print_r($post_vars, true)." </br> CART: ".print_r($orderItems, true));
}
